package com.jack.lib.core.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;


import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by chong on 2017/9/20.
 */

public class PackageInfoUtils {


    /**
     * 服务是否在运行
     * @param serivce
     * @param context
     * @return
     */
    public static boolean isServiceRunning(Class serivce , Context context){

        final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serivce.getName())){
                return true;
            }
        }
        return false;
    }


    /**
     * 检测该包名所对应的应用是否存在
     * * @param packageName
     *
     * @return
     */
    public static boolean checkPackage(Context context, String packageName) {
        return checkPackage(context, packageName, false);
    }

    public static boolean checkPackage(Context context, String packageName, boolean isDownload) {
        if (packageName == null || "".equals(packageName)) return false;
        try {
            //手机已安装，返回true
            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            //手机未安装，跳转到应用商店下载，并返回false

            if (isDownload) {
                Uri uri = Uri.parse("market://details?id=" + packageName);
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(it);
            }
            return false;
        }
    }

    public static String getIPAddress(Context context) {
        try {
            ConnectivityManager systemService = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = systemService.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                    try {
                        //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                                InetAddress inetAddress = enumIpAddr.nextElement();
                                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                    return inetAddress.getHostAddress();
                                }
                            }
                        }
                    } catch (SocketException e) {
                        e.printStackTrace();
                    }

                } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                    WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                    return ipAddress;
                }
            } else {
                //当前无网络连接,请在设置中打开网络
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }



    /**
     * 跳转到天猫商品详情
     */
    public static void openTianmaoGoods(Context context, String goodsId){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String id = "539789035577";
        String url = "tmall://tmallclient/?{\"action\":”item:id=" + goodsId + "”}";
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 跳转到天猫店铺
     */
    public static void openTianmaoStore(Context context, String storeId){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String id = "539789035577";
        String url="tmall://page.tm/shop?shopId="+ storeId;
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 跳转到淘宝商品详情
     */
    public static void openTaobaoGoods(Context context, String goodsId){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String id = "539789035577";
        String url = "https://item.taobao.com/item.htm?id=" + goodsId + "&ali_refid=a3_430406_1007:1124066525:N:485184283370953001_0_100" +
                ":d45485b3013535b0cc4164b7cd5b7523&ali_trackid=1_d45485b3013535b0cc4164b7cd5b7523&spm=a21bo.50862.201874-sales.8.UYm99R";
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        intent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
        context.startActivity(intent);
    }

    /**
     * 跳转到淘宝店铺
     */
    public static void openTaobaoStore(Context context, String storeId){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        String url = "taobao://shop.m.taobao.com/shop/shop_index.htm?shop_id=" + storeId + "&spm=a230r.7195193.1997079397.8.Pp3ZMM&point" +
                "=%7B%22from%22%3A%22h5%22%2C%22url%22%3A%22http%3A%2F%2Fshop131259851.m.taobao.com%2F%22%2C%22h5_uid%22%3A%22aJHIDr" +
                "hLh0cCAYYbRtrrS3Ut%22%2C%22uaPoint%22%3A%22Mozilla%2F5.0%2520(Linux%3B%2520Android%25205.0.1%3B%2520SM-N9109W%2520Bui" +
                "ld%2FLRX22C%3B%2520wv)%2520AppleWebKit%2F537.36%2520(KHTML%2C%2520like%2520Gecko)%2520Version%2F4.0%2520Chrome%2F43" +
                ".0.2357.121%2520Mobile%2520Safari%2F537.36%2520Rong%2F2.0%22%7D";
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 跳转到京东商品详情
     */
    public static void openJingdongGoods(Context context, String goodsId){
        String id = "231023";//需要提取商品id，添加到下面url，不能单独将商品详情页作为url传入
        String url = "openapp.jdmobile://virtual?params=%7B%22sourceValue%22:%220_productDetail_97%22,%22des%22:%22productDetail%22," +
                "%22skuId%22:%22" + goodsId + "%22,%22category%22:%22jump%22,%22sourceType%22:%22PCUBE_CHANNEL%22%7D";
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }
}
